
#include "NetworkWrapper.h"
#include "NetworkException.h"

NetworkWrapper::NetworkWrapper()
{
}

NetworkWrapper::~NetworkWrapper()
{
}

void NetworkWrapper::init()
{
    SDLNet_Init();
}

void NetworkWrapper::quit()
{
    SDLNet_Quit();
}

TCPsocket NetworkWrapper::openServerSocket()
{
    return openSocket(NULL);
}

TCPsocket NetworkWrapper::openClientSocket(const std::string& serverIp)
{
    return openSocket(serverIp.c_str());
}

void NetworkWrapper::closeSocket(TCPsocket socket)
{
    if (socket != NULL)
    {
        SDLNet_TCP_Close(socket);
    }
}

TCPsocket NetworkWrapper::acceptConnection(TCPsocket serverSocket)
{
    checkSocket(serverSocket);
    return SDLNet_TCP_Accept(serverSocket);
}

void NetworkWrapper::receiveFrom(TCPsocket socket, void* data, size_t size)
{
    checkSocket(socket);
    int bytesRecieved = SDLNet_TCP_Recv(socket, data, size);
    if (bytesRecieved <= 0)
    {
        throw NetworkException("TCP data reception failed.");
    }
}

void NetworkWrapper::checkSocket(TCPsocket socket)
{
    if (socket == NULL)
    {
        throw NetworkException("Invalid socket.");
    }
}

void NetworkWrapper::sendTo(TCPsocket socket, void* data, size_t size)
{
    checkSocket(socket);
    SDLNet_TCP_Send(socket, data, size);
}

TCPsocket NetworkWrapper::openSocket(const char* hostIp)
{
    IPaddress ip;
    int result = SDLNet_ResolveHost(&ip, hostIp, 2000);
    if (result < 0)
    {
        throw NetworkException("Failed to open socket.");
    }
    TCPsocket socket = SDLNet_TCP_Open(&ip);
    checkSocket(socket);
    return socket;
}
